<!-- 药材选择器 -->
<template>
  <el-select
    v-model="currentID"
    v-loadMore="selectLoadMore"
    filterable
    remote
    placeholder="请选择药材,可输入药材名搜索选择"
    clearable
    @change="handleChange"
    :remote-method="remoteMethod"
    :loading="loading"
    style="width: 100%;"
  >
    <el-option
      v-for="item in options"
      :key="item[valueKey]"
      :label="item.name + `(${item.code})`"
      :value="item[valueKey]"
    ></el-option>
  </el-select>
</template>

<script>
import { getDrugList, getDrugDetails } from '@/api/saas/tcm.js'
import { arrayUnique } from '@/utils/ruoyi'

export default {
  props: {
    defaultValue: {
      type: Number | String
    },
    // id || code
    valueKey: {
      type: String,
      default: 'id'
    },
    status: {
      type: Number | String
    }
  },
  watch: {
    defaultValue(nval){
      this.currentID = nval;
      this.backShow(); // 回显
    }
  },
  data () {
    return {
      currentID: null,
      options: [],
      getParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: undefined,
      },
      total: 0,
      loading: false
    };
  },
  async created() {
    this.currentID = this.defaultValue;
    await this.getList();
    this.backShow(); // 回显
  },
  methods: {
    async getList() {
      const { rows, total } = await getDrugList({...this.getParams, status: this.status });
      this.total = total;
      if(this.getParams.pageNum === 1){ this.options = [] };
      this.options = arrayUnique([...this.options, ...rows], this.valueKey);
    },
    // 下拉加载更多
    selectLoadMore() {
      if(this.options.length < this.total){
        this.getParams.pageNum++;
        this.getList();
      }
    },
    async remoteMethod(query){
      this.loading = true;
      this.getParams.pageNum = 1;
      this.getParams.pageSize = 10;
      this.getParams.keyword = query;
      await this.getList();
      this.loading = false;
    },
    handleChange(e){
      this.$emit('update:defaultValue', e);
      this.$emit('change', e);
    },
    // 回显判断,是否存在于数组中,不存在则查询详情unshift进去
    backShow(){
      if(this.currentID){
        const _item = this.options.find(v=> v[this.valueKey] === this.currentID);
        if(!_item){
          if(this.valueKey === 'id'){
            getDrugDetails(this.currentID).then((res)=>{
              if(res.data){
                this.options = arrayUnique([res.data,...this.options], this.valueKey);
              }
            })
          }else{
            getDrugList({pageNum: 1, pageSize: 10, code: this.currentID}).then(res=>{
              if(res.rows){
                this.options = arrayUnique([...res.rows,...this.options], this.valueKey);
              }
            })
          }
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
